//辅助类
/**
 * 商品条件
 * @param categoryId
 * @param price
 * @constructor
 */
function Condiction(categoryId, price) {
    this.categoryId = categoryId;
    this.price = price;
}


//辅助功能------------------------------------------------------------------------
/**
 * sweetalert的封装
 * @param title 标题
 * @param msg 内容
 * @param type 类型
 */
function swl(title,msg,type) {
    sweetAlert({
        title:title,
        content:msg,
        type:type
    })
}
/**
* 视图渲染
* @Param where 渲染位置
* @Param templateName 模板名
* @Param data 渲染数据
* */
function viewToTemplate(where,templateName,data) {
    var html = $('script[type="text/'+templateName+'"]').html();//模板代码
    var arr=[];
    $("#"+where).html("");//清空tbody
    $.each(data, function (index, object) {
        arr.push(formatTemplate(object, html));
    });
    $("#"+where).append(arr.join(""));
}
function formatTemplate(object, tmpl,fun) {
    //m1 匹配到的字符{W} m2 字符的内容 W
    return tmpl.replace(/{(\w+)}/g,function (m1, m2) {
        if(!m2){
            return "";
        }
        if (typeof fun == 'function' ){
            fun();
        }
        return object[m2];
    })
}
/**
 * 分页+视图渲染
 * @param id 渲染位置
 * @param templateName 模板名称
 * @param data 数据渲染
 */
function viewToPage(id, templateName, data,categoryId){
    var res = data.extend.productList;
    priceAdopt(res.list)
    viewToTemplate(id,templateName,res.list)
    makePage(res,categoryId);
    build_page_nav(res,categoryId);
}
/**
 * 获取时间
 * @param cellval
 * @returns {string}
 * @constructor
 */
function ChangeDateFormat(cellval) {
    var date = new Date(parseInt(cellval, 10));
    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    return date.getFullYear() + "-" + month + "-" + currentDate;
}
/**
 * 分页
 */
function makePage(result){
    $("#page_Info").empty();
    var center=$("<center></center>").append("当前第"+result.pageNum+"页,总共"+result.pages+
        " 页,总"+result.total+" 条数记录");
    $("#page_Info").append(center);

}
function build_page_nav(result,categoryId){
    $("#page_nav").empty();
    var ul=$("<ul></ul>").addClass("pagination");
    var firstPage=$("<li></li>").append($("<a></a>").append("首页").attr("href","#"));
    var prePage=$("<li></li>").append($("<a></a>").append("&laquo;").attr("href","#"));
    if(result.hasPreviousPage==false){
        firstPage.addClass("disabled");
        prePage.addClass("disabled");
    }else{
        //为元素添加点击事件
        firstPage.click(function(){
            to_Page(1,categoryId);
        });
        prePage.click(function(){
            to_Page(result.pageNum-1,categoryId);
        });
    }


    var nextPage=$("<li></li>").append($("<a></a>").append("&raquo;").attr("href","#"));
    var lastPage=$("<li></li>").append($("<a></a>").append("末页").attr("href","#"));
    if(result.hasNextPage==false){
        nextPage.addClass("disabled");
        lastPage.addClass("disabled");
    }else{
        lastPage.click(function(){
            to_Page(result.pages,categoryId);
        });
        nextPage.click(function(){
            to_Page(result.pageNum+1,categoryId);
        });
    }


    ul.append(firstPage).append(prePage);
    $.each(result.navigatepageNums,function(index,item){
        var num=$("<li></li>").append($("<a></a>").append(item).attr("href","#"));
        if(result.pageNum==item){
            num.addClass("active");
        }
        num.click(function(){
            to_Page(item,categoryId);
        });
        ul.append(num);
    });
    ul.append(nextPage).append(lastPage);
    var nav=$("<nav></nav>").addClass("Page navigation").append(ul);
    nav.appendTo("#page_nav");
}
/**
 * 分页跳转
 * @param pn 跳转页数
 */
function to_Page(pn, categoryId){
    var data;
    if(categoryId === null || categoryId === undefined ){
        data = {"pn":pn};
    }else {
        data = {"pn":pn, "categoryId":categoryId};
    }
    $.ajax({
        url:"/product/getProducts",
        data:data,
        type:"post",
        success:function(result){
            viewToPage("profile","list_view_template",result,categoryId);
            viewToPage("list_view_template","list_view_template",result,categoryId);
        }
    })
}
/**
 * 价格改变
 * @param data
 * @returns {*}
 */
function priceAdopt(data) {
    for (var i=0;i <data.length; i++){
        data[i].price /= 100;
    }
    return data;
}

/**
 * 渲染一级分类
 * @param data
 * @param num
 */
function firstCategoryRender(data,num) {
    var res = [];
    for (var i=0; i<num-1; i++){
        res[i] = data[i];
    }
    viewToTemplate("category_list","categoryParent_list_template",res);
    $("#category_list").append('<li class="showmore-items shwitm" onclick="getMoreCategory()">\n' +
        '<i class="fa fa-plus-square-o"></i>\n' +
        '<span id="More_categories_click">更多分类</span>\n' +
        '</li>');
}
//功能--------------------------------------------------------------------------------------------------------------------------------------------------------
/**
 * 通过分类号查询商品
 * @param categoryId 分类号
 */
function getProducts(categoryId,id) {
    var data;
    if (categoryId === null) {
        data = null;
    }else {
        data = {"categoryId":categoryId};
    }
    $.ajax({
        url:"/product/getProducts",
        type:"post",
        data:data,
        success:function (res) {
            viewToPage("profile","list_view_template",res,categoryId);
            viewToPage("list_view_template","list_view_template",res,categoryId);
        }
    })
}

/**
 * 通过分类id或者产品id查询产品
 * @param categoryId
 * @param id
 */
function getProudctsByCondiction(categoryId,id){
    var data={};
    if(categoryId !== undefined || categoryId !== null) {
        data.categoryId = categoryId;
    }
    if (id !== undefined || id !== null) {
        data.id = id;
    }
    $.ajax({
        url:"/product/getProductById",
        type:"post",
        data:data,
        success:function (result) {
           quick_view(result);
        }
    })
}

/**
 * 一级分类获取
 */
function getParentCategory(){

    $.ajax({
        url:"/category/queryCategories",
        type:"post",
        data:{"isParent":1},
        success:function (res) {
            if(res.code == "200 ") {
                firstCategoryRender(res.extend.list,6)
            }else {
                console.log(res);
            }
        }
    })
}

/**
 * 二级分类获取
 */
function getChildCategory(id){
    $.ajax({
        url:"/category/queryCategories",
        type:"post",
        data:{"parentId":id,"isParent":0},
        success:function (res) {
            if(res.code == "200") {
                viewToTemplate("categoryChild_list_menu_"+id,"categoryChild_list_template",res.extend.list)
            }else {
                console.log(res);
            }
        }
    })

}
/**
 * 根据id清除内容
 * @param id
 */
function clearCategoryHmtl(id){
    $("categoryChild_list_menu_"+id).html("")
}

/**
 * 通过分类查询产品
 * @param parentId
 */
function getProductsByCategoryId(parentId){
    getProducts(parentId);
}

/**
 * 快速查看
 * @param data
 */
function quick_view(data){
    data = data.extend.product;
    $("#quick_view_img").attr("src",data.image);
    $("#quick_view_title").html(data.title);
    $("#quick_view_price").html("价格：￥"+data.price/100+".00");
    $("#quick_view_id").attr("productId",data.id);
    $("#myModal").modal('show')
}
function add_product_to_cart_quick_view(id) {
    var num = $("")
}
/**
 *添加商品到购物车 默认
 */
function add_product_cart(){
    var id = $("#quick_view_id").attr("productId"),
        num = $("#quick_view_num").val();
    add_product(id,num);
}

/**
 * 添加到购物车
 * @param id
 * @paren num
 */
function add_product(id,num){
    var data = {};
    data.productId = id;
    if(num !== null || num !== undefined) {
        data.num = num;
    }
    console.log(data)
    $.ajax({
        url:"/auth/addShopping",
        type:"post",
        data:data,
        success:function (res) {
            if(res.code == "200"){
                swl("成功","添加成功","success");
                $("#myModal").modal("hide");
            }else {
                alert("失败")
            }
        },
        error:function (res) {
            sweetAlert({
                title:"提示",
                text:"还没有登陆",
                type:"warning",
                showCancelButton:false,
                confirmButtonColor:"#dd6b55",
                closeOnConfirm:false
            },function () {
                window.location.assign("/login")
            })
        }
    })
}

/**
 * 获取更多的分类
 */
function getMoreCategory(){
    $.ajax({
        url:"/category/queryCategories",
        type:"post",
        data:{"isParent":1},
        success:function (res) {
            if(res.code == "200 ") {
                firstCategoryRender(res.extend.list,10)
            }else {
                console.log(res);
            }
        }
    })
}
//预加载----------------------------------------------------------------
$(document).ready(function () {
    //获取所有商品
    getProducts(null);
    //获取一级分类
    getParentCategory();
    //模态关闭事件
    $("#myModal").on('hide.bs.modal',function () {
        $("#quick_view_img").attr("src","");
        $("#quick_view_title").html("");
        $("#quick_view_price").html("");
        $("#quick_view_id").attr("productId","");

    })
})
